<template>
  <div class="table-assist">
    <je-modal
      v-model:visible="visibleModule"
      :title="assistType == 'userAssist' ? '人员辅助' : '表辅助'"
      width="1385px"
      class="assist-model"
      height="600"
      :resize="false"
      @close="cancelModal"
    >
      <template #buttons="modal">
        <je-button
          key="save"
          type="primary"
          :disabled="btnDisabled"
          :loading="btnLoading"
          @click="addModule(modal)"
        >
          确定
        </je-button>
        <je-button key="back" @click="cancelModal">取消</je-button>
      </template>
      <je-panel v-bind="options">
        <template #top>
          <div class="top-explain">
            <p class="explain-one">通过其他表资源辅助完成字段添加操作。</p>
            <p class="explain-two">可选【查询选择入口、自动外键】按需定制。</p>
          </div>
        </template>
        <template #default>
          <div style="height: 100%">
            <je-table
              ref="xTable"
              :data="tableStore"
              show-overflow="ellipsis"
              stripe
              :row-config="{ isCurrent: true, isHover: true }"
              style="height: 100%"
              border
              keep-source
              :cell-style="cellStyle"
              resizable
              :edit-config="{
                trigger: 'click',
                mode: 'cell',
                showStatus: false,
              }"
            >
              <je-column type="seq" title="No" width="50" align="center"></je-column>
              <je-column
                field="TABLECOLUMN_NAME"
                title="预添加列名称"
                width="170"
                :edit-render="inputRender"
              >
                <template #header>
                  <span style="color: #3265f5">预添加列名称</span>
                </template>
                <template #edit="{ row }">
                  <je-input v-model:value="row.TABLECOLUMN_NAME" />
                </template>
              </je-column>
              <je-column field="TABLECOLUMN_CODE" title="列编码" width="230"></je-column>
              <je-column
                field="TABLECOLUMN_NEWCODE"
                title="预添加列编码"
                :edit-render="inputRender"
              >
                <template #header>
                  <span style="color: #3265f5">预添加列编码</span>
                </template>
                <template #edit="{ row }">
                  <je-input v-model:value="row.TABLECOLUMN_NEWCODE" @change="changeVerify" />
                </template>
              </je-column>
              <je-column
                v-if="assistType != 'userAssist' && modelRef.TABLETYPE != 'VIEW'"
                field="TABLECOLUMN_ISCREATE"
                title="生成外键"
                width="80"
                align="center"
              >
                <template #default="{ row }">
                  <je-checkbox
                    v-if="row.TABLECOLUMN_TYPE == 'ID'"
                    v-model:checked="row.TABLECOLUMN_ISCREATE"
                  />
                </template>
              </je-column>
              <je-column field="TABLECOLUMN_ISNULL" title="查询选择入口" width="120" align="center">
                <template #default="{ row }">
                  <je-checkbox
                    v-if="!row.disabled"
                    v-model:checked="row.TABLECOLUMN_ISNULL"
                    @change="checkBoxChange(row)"
                  />
                </template>
              </je-column>
              <je-column field="TABLECOLUMN_TREETYPE" title="检查" width="50" align="center">
                <template #default="{ row }">
                  <!-- <i
              v-if="columnCodes.indexOf(row.TABLECOLUMN_CLASSIFY) != -1"
              class="jeicon jeicon-check-circle-s"
              style="color: red"
            ></i> -->
                  <i
                    class="jeicon jeicon-check-circle-s"
                    :style="`color: ${
                      columnCodes.indexOf(row.TABLECOLUMN_NEWCODE) != -1 ? '#D7D7D7' : '#8CBC5F'
                    }`"
                  ></i>
                </template>
              </je-column>
              <je-column title="操作" width="60" align="center">
                <template #default="{ row }">
                  <je-button type="text" @click="removeEvent(row)">
                    <template #icon
                      ><i style="margin-left: -3px" class="fal fa-times"></i
                    ></template>
                  </je-button>
                </template>
              </je-column>
              <template #tbar>
                <je-toolbar style="height: 50px; padding: 9px 0px 0px 0px">
                  <je-form layout="inline" style="height: 40px" :model="modelRef">
                    <je-form-item
                      label="表"
                      v-bind="validateInfos.TABLENAME"
                      name="TABLENAME"
                      width="241px"
                      validate-type="tooltip"
                    >
                      <je-tree-select
                        v-model:value="modelRef.TABLENAME"
                        width="203px"
                        :select-options="{ title: '资源表' }"
                        name="TABLENAME"
                        config-info="JE_META_PROJECTTABLE,TABLENAME~TABLECODE~TABLEID~TABLETYPE,text~code~id~nodeInfo,S"
                        :querys="getJQuery()"
                        :orders="[{ code: 'SY_ORDERINDEX', type: 'ASC' }]"
                        @select="selectTable"
                      />
                    </je-form-item>
                    <je-form-item
                      label="表编码"
                      v-bind="validateInfos.TABLECODE"
                      name="TABLECODE"
                      validate-type="tooltip"
                    >
                      <je-input v-model:value="modelRef.TABLECODE" :disabled="disabledInput" />
                    </je-form-item>
                    <je-form-item label="功能" name="FUNCNAME">
                      <!-- <je-input v-model:value="modelRef.FUNCNAME" :disabled="disabled" /> -->
                      <je-select
                        v-model:value="modelRef.FUNCNAME"
                        :options="checkBoxOptions"
                        name="FUNCNAME"
                        style="width: 187px"
                        :disabled="disabled"
                        :get-popup-container="getPopupContainer"
                        @change="selectChange"
                      ></je-select>
                    </je-form-item>
                    <je-form-item label="功能编码" name="FUNCCODE">
                      <je-input v-model:value="modelRef.FUNCCODE" :disabled="disabledInput" />
                    </je-form-item>
                    <je-button style="margin-right: 16px" @click="importColumn">
                      <template #icon><i class="fal fa-file-export"></i></template>
                      导入
                    </je-button>
                    <je-button @click="changeFieldPrefix">
                      <template #icon><i class="fal fa-file-export"></i></template>
                      {{ changeType ? '使用新表前缀' : '使用原表前缀' }}
                    </je-button>
                  </je-form>
                </je-toolbar>
              </template>
            </je-table>
          </div>
        </template>
      </je-panel>
    </je-modal>
  </div>
</template>

<script>
  import { defineComponent, ref, reactive } from 'vue';
  import {
    Input,
    Modal,
    Button,
    Grid,
    Checkbox,
    Form,
    InputSelect,
    Select,
    Toolbar,
    Panel,
  } from '@jecloud/ui';
  import {
    selectOne,
    getColumnData,
    addColumnByTable,
    viewColumnCode,
    getFuncInfoByTable,
    addTableAssistColumn,
  } from '../../api/index';
  import { verifyData } from '../../helper/common';
  import { debounce } from '@jecloud/utils';
  import { inputRender, numberRender } from '../../helper/edit-render';
  import { SelectWindow } from '@jecloud/func';

  const useForm = Form.useForm;
  export default defineComponent({
    name: 'TableAssist',
    components: {
      JeModal: Modal,
      JeInput: Input,
      JeForm: Form,
      JeFormItem: Form.Item,
      JeButton: Button,
      JeTable: Grid,
      JeColumn: Grid.Column,
      JeCheckbox: Checkbox,
      JeTreeSelect: InputSelect.Tree,
      JeSelect: Select,
      JeToolbar: Toolbar,
      JePanel: Panel,
    },
    props: {
      modalShow: {
        type: String,
        default: '',
      },
      modalData: {
        type: Object,
        default: () => {
          return {};
        },
      },
    },
    emits: ['changeData'],
    setup(props, { emit }) {
      const xTable = ref(null);
      const visibleModule = ref(true);
      const assistType = ref(props.modalShow);
      const parentData = reactive(props.modalData);
      const tableCode = parentData.RESOURCETABLE_TABLECODE;
      const tabelId = parentData.JE_CORE_RESOURCETABLE_ID;
      const btnDisabled = ref(false);
      const btnLoading = ref(false);
      const tableStore = ref([]);
      const columnCodes = ref([]);
      const checkBoxOptions = ref([]);
      const modelRef = reactive({
        TABLENAME: '',
        TABLECODE: '',
        TABLEID: '',
        FUNCNAME: '',
        FUNCCODE: '',
        TABLETYPE: '',
      });
      const disabled = ref(assistType.value == 'userAssist');
      const addModule = (modal) => {
        btnLoading.value = true;
        validate()
          .then(() => {
            const tableData = getXTable().getTableData().tableData;
            const insertData = [];
            const selfCodes = [];
            const targerCodes = [];
            let isQuery = false; //是否查询选择
            let isChild = '0'; //是否带有外键(添加子功能默认带入关联字段)

            if (tableData.length <= 0) {
              btnLoading.value = false;
              Modal.alert('请导入字段！', 'warning');
              return;
            }

            tableData.forEach((item) => {
              selfCodes.push(item.TABLECOLUMN_NEWCODE);
              targerCodes.push(item.TABLECOLUMN_CODE);
              insertData.push(item);
              if (item.TABLECOLUMN_ISNULL) {
                isQuery = true;
              }
              if (item.TABLECOLUMN_ISCREATE && assistType.value != 'userAssist') {
                isChild = '1';
              }
            });

            //数据转换
            insertData.forEach((item) => {
              item.TABLECOLUMN_ISNULL = item.TABLECOLUMN_ISNULL ? 1 : 0;
              if (assistType.value != 'userAssist') {
                item.TABLECOLUMN_ISCREATE = item.TABLECOLUMN_ISCREATE ? 1 : 0;
              }
            });

            const params = {
              tableCode: tableCode,
              JE_CORE_RESOURCETABLE_ID: tabelId,
              strData: JSON.stringify(insertData),
              CREATECHILD: isChild,
            };
            if (isQuery) {
              params.FUNCCODE = modelRef.FUNCCODE;
              params.queryStr = selfCodes.join('~') + ',' + targerCodes.join('~') + ',S';
            }

            //如果是人员辅助
            if (assistType.value == 'userAssist') {
              addColumnByTable(params)
                .then((data) => {
                  btnLoading.value = false;
                  modal.close();
                  emit('changeData', 'add');
                  Modal.notice(data.message, 'success');
                })
                .catch((e) => {
                  btnLoading.value = false;
                  columnCodes.value = e.data;
                  Modal.alert(e.message, 'error');
                });
            } else {
              addTableAssistColumn(params)
                .then((data) => {
                  btnLoading.value = false;
                  modal.close();
                  emit('changeData', 'add');
                  Modal.notice(data.message, 'success');
                })
                .catch((e) => {
                  btnLoading.value = false;
                  //columnCodes.value = e.data;
                  Modal.alert(e.message, 'error');
                });
            }
          })
          .catch((error) => {
            btnLoading.value = false;
          });

        return false;
      };

      const cancelModal = () => {
        emit('changeData');
      };

      //如果就人呢员辅助
      if (assistType.value == 'userAssist') {
        //查询表单数据
        selectOne({
          tableCode: 'JE_CORE_RESOURCETABLE',
          j_query:
            '{"custom":[{"type":"=","code":"RESOURCETABLE_TABLECODE","value":"JE_RBAC_VUSERQUERY"}]}',
        })
          .then((data) => {
            modelRef.TABLENAME = data.RESOURCETABLE_TABLENAME;
            modelRef.TABLECODE = data.RESOURCETABLE_TABLECODE;
            modelRef.TABLEID = data.JE_CORE_RESOURCETABLE_ID;
            modelRef.FUNCNAME = '人员查询';
            modelRef.FUNCCODE = 'JE_RBAC_VUSERQUERY';
            //查询列表数据
            getColumnData({
              tableCode: 'JE_CORE_TABLECOLUMN',
              limit: -1,
              j_query: JSON.stringify({
                custom: [
                  {
                    type: '=',
                    code: 'TABLECOLUMN_RESOURCETABLE_ID',
                    value: data.JE_CORE_RESOURCETABLE_ID,
                  },
                ],
              }),
            })
              .then((data) => {
                //列表数据处理
                let _columns = [],
                  names = tableCode.split('_');
                const preSuffix = names.pop();
                const fieldCodes = ['USER_ID', 'USER_NAME', 'DEPARTMENT_ID', 'DEPARTMENT_NAME'];
                const arraySort = (arr) => {
                  const field = 'TABLECOLUMN_CODE';
                  arr.sort(function (a, b) {
                    if (fieldCodes.indexOf(a[field]) < fieldCodes.indexOf(b[field])) {
                      return -1;
                    }
                    if (fieldCodes.indexOf(a[field]) > fieldCodes.indexOf(b[field])) {
                      return 1;
                    }
                    return 0;
                  });
                  return arr;
                };
                const verifyCodes = [];
                data.rows.forEach((col) => {
                  //字段特殊处理
                  if (col.TABLECOLUMN_CODE == 'USER_ID') {
                    col.TABLECOLUMN_NEWCODE = preSuffix + '_USER_ID';
                  } else if (col.TABLECOLUMN_CODE == 'USER_NAME') {
                    col.TABLECOLUMN_NEWCODE = preSuffix + '_USER_NAME';
                  } else if (col.TABLECOLUMN_CODE == 'DEPARTMENT_ID') {
                    col.TABLECOLUMN_NEWCODE = preSuffix + '_DEPT_ID';
                  } else if (col.TABLECOLUMN_CODE == 'DEPARTMENT_NAME') {
                    col.TABLECOLUMN_NEWCODE = preSuffix + '_DEPT_NAME';
                  } else {
                    col.TABLECOLUMN_NEWCODE = preSuffix + '_' + col.TABLECOLUMN_CODE;
                  }
                  col.TABLECOLUMN_ISNULL = col.TABLECOLUMN_CODE == 'USER_NAME';
                  //col.TABLECOLUMN_ISCREATE = col.TABLECOLUMN_CODE == 'USERID';
                  col.disabled = col.TABLECOLUMN_CODE != 'USER_NAME';
                  if (fieldCodes.indexOf(col.TABLECOLUMN_CODE) != -1) {
                    if (col.TABLECOLUMN_CODE == 'USER_ID') {
                      //col.TABLECOLUMN_ISCREATE = true;
                    }
                    _columns.push(col);
                    verifyCodes.push(col.TABLECOLUMN_NEWCODE);
                  }
                  // columnCodes.value.push(col.TABLECOLUMN_CODE);
                });
                var newColumns = arraySort(_columns);
                viewColumnCode({
                  JE_CORE_RESOURCETABLE_ID: tabelId,
                  addColumnCodes: verifyCodes.join(','),
                })
                  .then((obj) => {
                    btnDisabled.value = false;
                    tableStore.value = newColumns;
                  })
                  .catch((e) => {
                    btnDisabled.value = true;
                    columnCodes.value = e.data;
                    tableStore.value = newColumns;
                    //Modal.alert(e.message, 'error');
                  });
              })
              .catch((e) => {
                Modal.alert(e.message, 'error');
              });
          })
          .catch((e) => {
            Modal.alert(e.message, 'error');
          });
      }

      //表单信息初始化
      const rulesRef = reactive({
        TABLENAME: [verifyData.required],
        TABLECODE: [verifyData.required],
      });
      const { resetFields, validate, validateInfos } = useForm(modelRef, rulesRef, {
        onValidate: (...args) => {},
      });

      //根据条件改变单元格的样式
      const cellStyle = ({ row, column }) => {
        //生成外键列
        if (column.property === 'TABLECOLUMN_ISCREATE' && assistType.value != 'userAssist') {
          if (row.TABLECOLUMN_TYPE != 'ID') {
            return {
              backgroundColor: '#F2F2F2',
            };
          }
        }
        //查询选择入口列
        if (column.property === 'TABLECOLUMN_ISNULL') {
          if (row.disabled) {
            return {
              backgroundColor: '#F2F2F2',
            };
          }
        }
      };

      const removeEvent = (row) => {
        const $table = getXTable();
        $table.remove(row);
        getColumnVerify();
      };

      //查询选择入口值改变
      const checkBoxChange = (row) => {
        const tableData = getXTable().getTableData().tableData;
        //选中其他的disable = ture
        if (row.TABLECOLUMN_ISNULL) {
          tableData.forEach((record) => {
            if (row.JE_CORE_TABLECOLUMN_ID != record.JE_CORE_TABLECOLUMN_ID) {
              record.disabled = true;
            }
          });
          //取消选中全都的disable = flase,
        } else {
          tableData.forEach((record) => {
            record.disabled = false;
          });
        }
      };

      //字典判重校验
      const getColumnVerify = (codes) => {
        if (!codes) {
          codes = [];
          const tableData = getXTable().getTableData().tableData;
          tableData.forEach((item) => {
            codes.push(item.TABLECOLUMN_NEWCODE);
          });
          codes = codes.join(',');
        }
        viewColumnCode({
          JE_CORE_RESOURCETABLE_ID: tabelId,
          addColumnCodes: codes,
        })
          .then((obj) => {
            btnDisabled.value = false;
          })
          .catch((e) => {
            btnDisabled.value = true;
            columnCodes.value = e.data;
            //Modal.alert(e.message, 'error');
          });
      };

      //文本框值改变校验
      const changeVerify = debounce((searchValue) => {
        const tableData = getXTable().getTableData().tableData;
        const codes = [];
        tableData.forEach((item) => {
          codes.push(item.TABLECOLUMN_NEWCODE);
        });
        getColumnVerify(codes.join(','));
      }, 500);

      //改变字段前缀
      const changeType = ref(false);
      const changeFieldPrefix = () => {
        const codes = [];
        changeType.value = !changeType.value;
        const tableData = getXTable().getTableData().tableData;
        let prefix = '';
        let cutString = '';
        //使用原表做前缀
        if (changeType.value) {
          prefix = modelRef.TABLECODE.split('_').pop();
          cutString = tableCode.split('_').pop();
        } else {
          prefix = tableCode.split('_').pop();
          cutString = modelRef.TABLECODE.split('_').pop();
        }
        tableData.forEach((item) => {
          //表辅助 主键和外键的code值不变
          if (
            ['ID', 'FOREIGNKEY'].indexOf(item.TABLECOLUMN_TYPE) == -1 ||
            assistType.value == 'userAssist'
          ) {
            const shift = item.TABLECOLUMN_NEWCODE.split('_').shift();
            if (shift == cutString) {
              const suffixArray = item.TABLECOLUMN_NEWCODE.split('_');
              suffixArray.shift();
              item.TABLECOLUMN_NEWCODE = prefix + '_' + suffixArray.join('_');
            }
          }
          codes.push(item.TABLECOLUMN_NEWCODE);
        });
        getColumnVerify(codes.join(','));
      };

      //获得列表对象
      const getXTable = () => {
        return xTable.value.$plugin;
      };

      //分装j_query
      const getJQuery = () => {
        const j_query = [
          {
            code: 'RESOURCETABLE_TABLECODE',
            type: '!=',
            value: tableCode,
          },
          {
            code: 'RESOURCETABLE_ISCREATE',
            type: '=',
            value: '1',
            cn: 'and',
          },
        ];
        return j_query;
      };

      //表改变
      const selectTable = ({ rows }) => {
        if (rows && rows.length > 0) {
          const nodeType = rows[0].nodeInfo;
          if (['PT', 'TREE', 'VIEW'].indexOf(nodeType) == -1) {
            Modal.alert('请选择表!', 'error');
            return false;
          }
          modelRef.FUNCNAME = '';
          modelRef.FUNCCODE = '';
          const tableData = getXTable().getTableData().tableData;
          if (tableData && tableData.length > 0) {
            getXTable().remove(tableData);
          }
          modelRef.TABLECODE = rows[0].code;
          modelRef.TABLEID = rows[0].id;
          getFuncInfoByTable({ tableCode: 'JE_CORE_FUNCINFO', strData: rows[0].code })
            .then((obj) => {
              const arrays = [];
              obj.data.rows.forEach((item) => {
                arrays.push({ lable: item.text, value: item.text, code: item.code });
              });
              checkBoxOptions.value = arrays;
              if (arrays.length > 0) {
                modelRef.FUNCNAME = arrays[0].value;
                modelRef.FUNCCODE = arrays[0].code;
              }
            })
            .catch((e) => {
              Modal.alert(e.message, 'error');
            });
        }
      };

      //导入字段
      const importColumn = () => {
        if (modelRef.TABLECODE == '') {
          return Modal.alert('请先选择表！', 'error');
        }
        const j_query = [
          { type: '=', code: 'TABLECOLUMN_TABLECODE', value: modelRef.TABLECODE, cn: 'and' },
          { code: 'TABLECOLUMN_ISCREATE', type: '=', value: '1', cn: 'and' },
          {
            type: 'and',
            value: [
              { type: '!=', code: 'TABLECOLUMN_CLASSIFY', value: 'SYS' },
              { type: '=', code: 'TABLECOLUMN_TYPE', value: 'ID', cn: 'or' },
              {
                type: 'in',
                code: 'TABLECOLUMN_CODE',
                value: ['SY_JTGSMC', 'SY_JTGSID'],
                cn: 'or',
              },
              { type: 'like%', code: 'TABLECOLUMN_CODE', value: 'SY_CREATE', cn: 'or' },
            ],
          },
        ];
        const tableData = getXTable().getTableData().tableData;
        if (tableData && tableData.length > 0) {
          const codes = [];
          tableData.forEach((rec) => {
            codes.push(rec.TABLECOLUMN_CODE);
          });
          j_query.push({
            type: 'notIn',
            code: 'TABLECOLUMN_CODE',
            value: codes,
          });
        }
        SelectWindow.show({
          title: '表字段',
          type: 'grid',
          querys: j_query,
          orders: [
            { code: 'TABLECOLUMN_CLASSIFY', type: 'ASC' },
            { code: 'SY_ORDERINDEX', type: 'ASC' },
          ],
          configInfo: 'JE_CORE_TABLECOLUMN,,,M',
          callback: function ({ rows, config, $modal }) {
            getTableColumnData(rows);
          },
        });
      };

      //导入字段数据封装
      const getTableColumnData = (sels) => {
        let targerTableCode = modelRef.TABLECODE;
        let tableCode = parentData.RESOURCETABLE_TABLECODE;
        const tableName = modelRef.TABLENAME;
        if (tableCode.lastIndexOf('_') >= 0) {
          tableCode = tableCode.substring(tableCode.lastIndexOf('_') + 1);
        }
        if (targerTableCode.lastIndexOf('_') >= 0) {
          targerTableCode = targerTableCode.substring(targerTableCode.lastIndexOf('_') + 1);
        }
        const columnDatas = [];
        sels.forEach((row) => {
          var columnCode = row.TABLECOLUMN_CODE;
          var columnType = row.TABLECOLUMN_TYPE;
          if (
            ['ID', 'FOREIGNKEY'].indexOf(columnType) != -1 ||
            columnCode.indexOf(targerTableCode + '_') != 0
          ) {
            //主键 || 外键 || 没有使用表前缀的，用原始字段
            row.TABLECOLUMN_NEWCODE = columnCode;
            columnType == 'ID' && (row.TABLECOLUMN_NAME = tableName + '_外键ID');
          } else {
            //默认表字段
            row.TABLECOLUMN_NEWCODE = columnCode.replace(targerTableCode + '_', tableCode + '_');
            if (row.TABLECOLUMN_NEWCODE == columnCode) {
              row.TABLECOLUMN_NEWCODE = tableCode + '_' + columnCode;
            }
          }
          row.TABLECOLUMN_ISCREATE = false;
          row.TABLECOLUMN_ISNULL = false;
          columnDatas.push(row);
        });
        getXTable().insertAt(columnDatas, -1);
        getColumnVerify();
      };

      //选择功能功能编码重新赋值
      const selectChange = (obj, option) => {
        modelRef.FUNCCODE = option.code;
      };

      const getPopupContainer = () => {
        return document.body;
      };

      return {
        visibleModule,
        cancelModal,
        addModule,
        validateInfos,
        resetFields,
        modelRef,
        tableStore,
        removeEvent,
        assistType,
        disabled,
        columnCodes,
        centered: true,
        disabledInput: true,
        cellStyle,
        checkBoxChange,
        getXTable,
        btnDisabled,
        btnLoading,
        xTable,
        changeVerify,
        changeFieldPrefix,
        changeType,
        inputRender,
        numberRender,
        getJQuery,
        selectTable,
        checkBoxOptions,
        importColumn,
        selectChange,
        options: { top: { size: 80 } },
        getPopupContainer,
      };
    },
  });
</script>

<style lang="less" scoped>
  .assist-model {
    .top-explain {
      height: 80px;
      background: #f9f9f9;
      margin-bottom: 10px;
      padding: 14px 26px;
      .explain-one {
        font-size: 14px;
        line-height: 22px;
        color: #606060;
        font-weight: Normal;
      }
      .explain-two {
        font-size: 14px;
        font-weight: Normal;
        color: #0000ff;
        line-height: 0px;
      }
    }
  }
</style>
